//
//  AYuNetworkTools.swift
//  SHWeibo3
//
//  Created by 余伟康 on 16/7/22.
//  Copyright © 2016年 wangce. All rights reserved.
//

import UIKit
import AFNetworking
// 请求方式的枚举
enum AYuNetworkToolsType: String {
    case GET = "GET"
    case POST = "POST"
}
class AYuNetworkTools: AFHTTPSessionManager {
    // 全局访问点
    static let sharedTools: AYuNetworkTools = {
        let tools = AYuNetworkTools()
        // 指定反序列化格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    // 网络请求支持get和post请求公共方法
    /// 请求公共方法
    ///
    /// - parameter type:       请求方式
    /// - parameter urlString:  请求url
    /// - parameter parameters: 请求参数
    /// - parameter success:    成功的闭包
    /// - parameter failure:    失败的闭包
    func request(type: AYuNetworkToolsType, urlString: String, parameters: AnyObject?, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // get请求
        if type == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }else {
            // post 请求
            POST(urlString, parameters: parameters, progress: nil, success: { (_, res) -> Void in
                success(response: res)
                }, failure: { (_, err) -> Void in
                    failure(error: err)
            })
        }
        
    }
    
}
// MARK: - 请求OAuth界面数据
extension AYuNetworkTools{
    // 请求userAccount
    func oauthLoadUserAccount(code: String, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
            "client_id": APPKEY,
            "client_secret": APPSECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": APPREIRECT_URI
        ]
        request(AYuNetworkToolsType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    // 请求用户信息数据
    func oauthLoadUserInfo(userAccount: AYuUserAccount, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求的urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token": userAccount.access_token!,
            "uid": userAccount.uid!
        ]
        request(AYuNetworkToolsType.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}


// MARK: - 请求首页微博界面数据
extension AYuNetworkTools{
    func homeLoadData(sinceId: Int64, maxId: Int64,success:(resoponse:AnyObject?)->(),failure:(error:NSError)->()){
        // 请求urlString
        let urlString =  "https://api.weibo.com/2/statuses/home_timeline.json"

        // 请求参数
        let params = ["access_token":AYuUserAccountViewModel.sharedTools.accessToken!,
            "since_id":"\(sinceId)",
            "max_id":"\(maxId)"
        ]
        

        
        request(.GET, urlString: urlString, parameters: params, success: success, failure: failure)
    }
}


// MARK: - 发送微博
extension AYuNetworkTools {
    // 发送文字微博
    func composeUpdate(status: String, success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求的urlString
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 请求参数
        let params = [
            "access_token":AYuUserAccountViewModel.sharedTools.accessToken!,
            "status":status
        ]
        request(AYuNetworkToolsType.POST, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    // 发送图片微博
    func composeUpload(status: String, imageList: [UIImage], success: (response: AnyObject?)->(), failure: (error: NSError)->()){
        // 请求urlString
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求参数
        let params = [
            "access_token":AYuUserAccountViewModel.sharedTools.accessToken!,
            "status":status
        ]
        // 请求必须用POST方式提交，并且注意采用multipart/form-data编码方式；
        POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            
            /*
            - 01参数: 客户端需要提交的二进制文件
            - 02参数: 服务器端给客户端提供的名字 服务器才知道你传的是什么模块里面的图片
            - 03参数: 服务器端保存文件的文件夹  客户端 可以随意传
            - 04参数: 代表客户端提交的二进制文件格式 一般可以使用该类型 application/octet-stream 忽略格式
            */
            // 获得二进制数据
            // 发送一张图片
            //            let data = UIImagePNGRepresentation(self.composePictureView.imageList.first!)!
            //            formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
            
            // 发送多张图片
            for i in 0..<imageList.count {
                let data = UIImagePNGRepresentation(imageList[i])!
                formdata.appendPartWithFileData(data, name: "pic", fileName: "oooo", mimeType: "application/octet-stream")
            }
            
            }, progress: nil, success: { (_, response) -> Void in
                success(response: response)
            }) { (_, error) -> Void in
                failure(error: error)
        }
    }
    
}












